﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HotShot.Entities;

namespace HotShot.Service.BusinessLogic.MessageProcessors
{
    public class RetrieveResultInternalProcessor : MessageProcessorBase  
    {
        public override void ProcessMessage(HotShot.Entities.Messages.BaseMessage message, string correlationId)
        {
            var entity = message.XmlPayload.FromXml<StorageEntity>();
            var result = MessageCorrelationLogic.Current.AddCorrelatedMessage(correlationId, message.SenderAddress, message);

            if (result == null)
                return;

            if(result.ResponseReady(MessagingLogic.Current.RetrieveThreshold) && !result.IsProcessed) 
            {
                // double locking to avoid reentering
                lock (result)
                {
                    if (result.IsProcessed)
                        return;

                    result.IsProcessed = true;

                    List<StorageEntity> entities = result.Responses.Where(i => i.Value != null).Select(i => i.Value.XmlPayload.FromXml<StorageEntity>()).ToList();
                    var maxTicks = entities.Max(i => i.Ticks);
                    entities = entities.Where(i => i.Ticks == maxTicks).ToList();

                    entities = entities.Distinct(new EntityPayloadComparer()).ToList();

                    entities.ForEach(i =>
                    {
                        i.StoreCount = result.ResponseTotal;
                        i.StoreIndex = result.ResponseCount;
                    });
                    QueueCommunicationLogic.Current.SendOutputMessage(Messages.RetrieveResult(entities), correlationId);

                    MessageCorrelationLogic.Current.FinalizeCorrelation(correlationId);
                }
            }
        }
    }
}
